package com.xe.framework;

import java.util.ArrayList;

import com.baidu.mapapi.BMapManager;
import com.xe.icard.Config;
import com.xe.map.GeneralListener;
import android.app.Activity;
import android.app.Application;
import android.os.Handler;

/**
 * 多activity应用框架
 * 
 * @author xujh
 * 
 */
public class XEApp extends Application {

	public static final String TAG = "IMPP";
	/**
	 * 唯一的实例，application只会有一个
	 */
	private static XEApp mIns = null;

	/**
	 * 记录所有创建的activity
	 */
	private ArrayList<Activity> mActivityList = null;

	/**
	 * 管理activity窗口的
	 */
	private XEActivityManager mActivityMan = null;

	/**
	 * 当前正在显示的activity
	 */
	private Activity mCurrentActivity = null;

	/**
	 * 地图
	 */
	private BMapManager mBMapMan;
	private static final String BAIDUMAP_KEY = "355B9BE9F5975B2EED6EB4DEF23CB6E9F1AD5ABC";
	
	//private DataContext mRuntimeData;
	
	/**
	 * 获取该应用唯一的实例
	 * 
	 * @return
	 */
	public static XEApp getInstance() {
		return mIns;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		mIns = this;
		mActivityMan = new XEActivityManager();
		mActivityList = new ArrayList<Activity>();
		
		mBMapMan = new BMapManager(this);
		mBMapMan.init(BAIDUMAP_KEY, new GeneralListener(getApplicationContext()));
		//mBMapMan.getLocationManager().setNotifyInternal(10, 5);//1.3.35才有效
		mBMapMan.start();
		
		Config.initConfig();
	}
	
	@Override
	public void onTerminate() {
		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}
		
		super.onTerminate();
	}
	
	/**
	 * 获取activity的管理器
	 * 
	 * @return
	 */
	public XEActivityManager getActivityManager() {
		return mActivityMan;
	}

	/**
	 * 在每个activity的onCreate方法中调用，
	 * 
	 * @param activity
	 */
	protected void addActivity(Activity activity) {
		mActivityList.add(activity);
	}

	/**
	 * 在每个activity被销毁时移除
	 * 
	 * @param activity
	 */
	protected void removeActivity(Activity activity) {
		mActivityList.remove(activity);
	}

	/**
	 * 完美退出app程序，关闭所有开辟的activity。
	 */
	public void exit() {
		if (mActivityList != null) {
			Activity activity;

			for (int i = 0; i < mActivityList.size(); i++) {
				activity = mActivityList.get(i);

				if (activity != null) {
					if (!activity.isFinishing()) {
						activity.finish();
					}

					activity = null;
				}
			}
		}
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	/**
	 * 仅在系统handler处理时会调用，其他应用不推荐使用该方法
	 * 
	 * @return
	 */
	public Activity getCurrentActivity() {
		return mCurrentActivity;
	}

	/**
	 * 每一个activity在进入onresume的时候调用
	 * 
	 * @return
	 */
	protected void setCurrentActivity(Activity mCurrentActivity) {
		this.mCurrentActivity = mCurrentActivity;
	}

	/**
	 * 返回地图管理器 
	 * @return
	 */
	public BMapManager getMapManager(){
		return mBMapMan;
	}

}
